package com.progenies.ecg.asm31.model.codeparts.lines;

import org.objectweb.asm.Opcodes;

import com.progenies.ecg.asm31.util.BytecodeInstructionsUtils;
import com.progenies.ecg.asm31.util.GenerationUtils;
import com.progenies.ecg.asm31.util.VariableRegister.Variable;


public class IncrementVariable extends ConfigurableLineCodePart {

	private String variableName;
	private int increment;

	public IncrementVariable(String variableName, int increment)
	{
		this.variableName=variableName;
		this.increment=increment;
	}

	@Override
	public void generateBytecode()
	{
		//no increment, no code.
		if(increment==0)
			return;
		
		
		Variable var=varRegister.getVariable(variableName);
		
		if(var.isLocal())
			visitor.visitIincInsn(var.getIndex(), increment);
		else
		{
			//get variable value into stack
			if(!var.isStatic())
			{
				BytecodeInstructionsUtils.insertLocalVariableIntoStack(visitor, varRegister, "this");
				visitor.visitInsn(Opcodes.DUP); //one for GETFIELD, one for PUTFIELD
			}
			
			visitor.visitFieldInsn(var.isStatic()?Opcodes.GETSTATIC:Opcodes.GETFIELD, GenerationUtils.getFieldOwner(variableName, parent), variableName, var.getType().getDescriptor());
			
			//add or sub?
			
			//insert increment into stack (positive)
			BytecodeInstructionsUtils.insertIntIntoStack(visitor, Math.abs(increment));
			
			//sum values
			visitor.visitInsn(var.getType().getOpcode(increment>0?Opcodes.IADD:Opcodes.ISUB));
			
			//store value
			visitor.visitFieldInsn(var.isStatic()?Opcodes.PUTSTATIC:Opcodes.PUTFIELD, GenerationUtils.getFieldOwner(variableName, parent), variableName, var.getType().getDescriptor());
		}
	}


}
